<?php
namespace Home\Controller;

use Think\Controller;

class UserController extends Controller{
    /**
     * 注册页面
     */
    public function register(){
        $this->display();
    }

    /**
     * 注册处理函数
     */
    public function registerHandle(){
        $password = I('post.password');
        $repeat_password = I('post.repeat_password');
        $name = I('post.name');
        $email = I('post.email');
        $tel = I('post.tel');
        if($password != $repeat_password){
            $this->error('两次输入的密码不一致');
        }
        $User = D('User');
        if($User->register($name, $email, $tel, $password) == false){
            $this->error('注册失败');
        }
        $this->success('注册成功', U('Home/User/login'));
    }

    /**
     * 登录页面
     */
    public function login(){
        if(session('?user_id')){
            $this->redirect('Home/Index/index');
        }
        $this->display();
    }

    /**
     * 登录处理函数
     */
    public function loginHandle(){
        $username = I('post.username');
        $password = I('post.password');
        $User = D('User');
        if(!($user_info = $User->checkUser($username, $password))){
            $this->error('用户名或密码错误');
        }
        session('user_id', $user_info['id']);
        session('user_name', $user_info['name']);
        session('user_email', $user_info['email']);
        session('user_tel', $user_info['tel']);
        $this->success('登录成功', U('Home/Index/index'));
    }

    /**
     * 注销操作
     */
    public function logout(){
        session(null);
        $this->redirect('Home/User/login');
    }

    /**
     * 修改密码页面
     */
    public function changePassword(){
        if(!session('?user_id')){
            $this->redirect('Home/User/login');
        }
        $this->display();
    }

    /**
     * 修改密码处理函数
     */
    public function changePasswordHandle(){
        $old_password = I('post.old_password');
        $new_password = I('post.new_password');
        $repeat_password = I('post.repeat_password');
        if($new_password != $repeat_password){
            $this->error('两次输入的密码不一致');
        }
        $User = D('User');
        if(!$User->checkUser(session('user_email'), $old_password)){
            $this->error('你输入的旧密码是错误的，请重试');
        }
        if($User->updatePassword(session('user_id'), $new_password) === false){
            $this->error('由于未知原因，你的密码修改失败，请确保周围没有坏人再次尝试~');
        }
        $this->success('恭喜你，密码修改成功~', U('Home/Index/index'));
    }

    /**
     * 找回密码页面
     */
    public function findPassword(){
        $this->display();
    }

    public function findPasswordHandle(){
        // 找回密码处理函数
    }
}
